/*
 * @Author: mayufo
 * @Date: 2020-02-14 14:48:06
 * @LastEditTime : 2020-02-14 17:18:28
 * @Description: 操作学生
 * @FilePath: /node/04/code/crud-express/student.js
 */

var fs = require('fs')
var dbPath = './db.json'
 

/**
 * @description: 获取全部数据
 * @param {type} 
 * @return: 
 */
exports.getData =  (callback) => {
    fs.readFile(dbPath, 'utf8', (err, students) => {
        if (err) {
            return callback(err)
        }
        callback(null, JSON.parse(students).students)
    })
}

/**
 * @description: 添加学生
 * @param {type} 
 * @return: 
 */
exports.addStduent = (item, callback) => {
    fs.readFile(dbPath, 'utf8', (err, students) => {
        if (err) {
            return callback(err)
        }
        var students = JSON.parse(students).students
        item.id = students[students.length - 1].id + 1

        students.push(item)

        var file = JSON.stringify({students: students})

        fs.writeFile(dbPath, file,  (err) => {
            if (err) {
                return callback(err)
            }
            callback(null)
        })
    })
}

/**
 * @description: 得到一个学生信息
 * @param {type} 
 * @return: 
 */
exports.getStudent = (id, callback) => {
    fs.readFile(dbPath, 'utf8', (err, students) => {
        if (err) {
            return callback(err)
        }
        var students = JSON.parse(students).students
        var student = students.find((item) => {
            return parseInt(id, 10) === parseInt(item.id, 10)
        })
        callback(null, student)
    })
}

/**
 * @description: 编辑学生资料
 * @param {type} 
 * @return: 
 */
exports.editStudent = (student, callback) => {
    fs.readFile(dbPath, 'utf8', (err, students) => {
        if (err) {
            return callback(err)
        }
        var students = JSON.parse(students).students
        student.id = parseInt(student.id, 10)

        var index = students.findIndex((item) => {
            return parseInt(student.id, 10) === parseInt(item.id, 10)
        })

        students[index] = JSON.parse(JSON.stringify(student))

        var file = JSON.stringify({students: students})

        fs.writeFile(dbPath, file,  (err) => {
            if (err) {
                return callback(err)
            }
            callback(null)
        })
    })
}

/**
 * @description: 删除
 * @param {type} 
 * @return: 
 */
exports.deleteStudent = (id, callback) => {
    fs.readFile(dbPath, 'utf8', (err, students) => {
        if (err) {
            return callback(err)
        }
        var students = JSON.parse(students).students

        var index = students.findIndex((item) => {
            return parseInt(item.id, 10) === parseInt(id, 10)
        })

        students.splice(index, 1)

        var file = JSON.stringify({students: students})

        fs.writeFile(dbPath, file,  (err) => {
            if (err) {
                return callback(err)
            }
            callback(null)
        })
    })
}